using Microsoft.AspNetCore.Mvc;
using ProcessManagementApi.DTOs;
using ProcessManagementApi.Services;
using MESData.ErrorCode;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ProcessManagementApi.Controllers
{
    /// <summary>
    /// 工艺流程管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ProcessFlowController : ControllerBase
    {
        private readonly IProcessFlowService _processFlowService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processFlowService">工艺流程服务</param>
        public ProcessFlowController(IProcessFlowService processFlowService)
        {
            _processFlowService = processFlowService;
        }

        /// <summary>
        /// 分页查询工艺流程列表
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns>工艺流程列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetProcessFlows([FromQuery] ProcessFlowQueryDto queryDto)
        {
            var result = await _processFlowService.GetProcessFlowsAsync(queryDto);
            return Ok(result);
        }

        /// <summary>
        /// 根据ID获取工艺流程详情
        /// </summary>
        /// <param name="id">工艺流程ID</param>
        /// <returns>工艺流程详情</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetProcessFlowById(int id)
        {
            var result = await _processFlowService.GetProcessFlowByIdAsync(id);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            if (result.Code == ApiEnum.NotFound)
            {
                return NotFound(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 创建工艺流程
        /// </summary>
        /// <param name="createDto">创建信息</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<IActionResult> CreateProcessFlow([FromBody] ProcessFlowCreateDto createDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _processFlowService.CreateProcessFlowAsync(createDto);
            if (result.Code == ApiEnum.Success)
            {
                return CreatedAtAction(nameof(GetProcessFlowById), new { id = result.Data!.Id }, result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 更新工艺流程
        /// </summary>
        /// <param name="updateDto">更新信息</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        public async Task<IActionResult> UpdateProcessFlow([FromBody] ProcessFlowUpdateDto updateDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _processFlowService.UpdateProcessFlowAsync(updateDto);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            if (result.Code == ApiEnum.NotFound)
            {
                return NotFound(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 删除工艺流程
        /// </summary>
        /// <param name="id">工艺流程ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteProcessFlow(int id)
        {
            var result = await _processFlowService.DeleteProcessFlowAsync(id);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            if (result.Code == ApiEnum.NotFound)
            {
                return NotFound(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 批量删除工艺流程
        /// </summary>
        /// <param name="ids">工艺流程ID列表</param>
        /// <returns>删除结果</returns>
        [HttpDelete("batch")]
        public async Task<IActionResult> BatchDeleteProcessFlows([FromBody] List<int> ids)
        {
            var result = await _processFlowService.BatchDeleteProcessFlowsAsync(ids);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 生成工艺流程编号
        /// </summary>
        /// <returns>生成的工艺流程编号</returns>
        [HttpGet("generate-code")]
        public async Task<IActionResult> GenerateProcessFlowCode()
        {
            var result = await _processFlowService.GenerateProcessFlowCodeAsync();
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 获取工艺流程的工序步骤
        /// </summary>
        /// <param name="id">工艺流程ID</param>
        /// <returns>工序步骤列表</returns>
        [HttpGet("{id}/steps")]
        public async Task<IActionResult> GetProcessFlowSteps(int id)
        {
            var result = await _processFlowService.GetProcessFlowStepsAsync(id);
            if (result.Code == ApiEnum.Success)
            {
                return Ok(result);
            }
            if (result.Code == ApiEnum.NotFound)
            {
                return NotFound(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 导出工艺流程步骤到Excel
        /// </summary>
        /// <param name="id">工艺流程ID</param>
        /// <returns>Excel文件</returns>
        [HttpPost("{id}/steps/export")]
        public async Task<IActionResult> ExportProcessFlowStepsToExcel(int id)
        {
            try
            {
                var excelData = await _processFlowService.ExportProcessFlowStepsToExcelAsync(id);

                // 获取工艺流程信息用于文件名
                var processFlowResult = await _processFlowService.GetProcessFlowByIdAsync(id);
                var fileName = $"工艺流程步骤_{processFlowResult.Data?.ProcessFlowName ?? id.ToString()}_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

                return File(excelData, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"导出失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 打印工艺流程详情到PDF
        /// </summary>
        /// <param name="id">工艺流程ID</param>
        /// <returns>PDF文件</returns>
        [HttpPost("{id}/print")]
        public async Task<IActionResult> PrintProcessFlowDetailsToPdf(int id)
        {
            try
            {
                var pdfData = await _processFlowService.PrintProcessFlowDetailsToPdfAsync(id);

                // 获取工艺流程信息用于文件名
                var processFlowResult = await _processFlowService.GetProcessFlowByIdAsync(id);
                var fileName = $"工艺流程详情_{processFlowResult.Data?.ProcessFlowName ?? id.ToString()}_{DateTime.Now:yyyyMMddHHmmss}.pdf";

                return File(pdfData, "application/pdf", fileName);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"打印失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 测试PDF生成功能
        /// </summary>
        /// <returns>测试PDF文件</returns>
        [HttpGet("test-pdf")]
        public IActionResult TestPdfGeneration()
        {
            try
            {
                using (var stream = new MemoryStream())
                {
                    var document = new Document(PageSize.A4, 50, 50, 50, 50);
                    var writer = PdfWriter.GetInstance(document, stream);
                    document.Open();

                    try
                    {
                        // 设置中文字体
                        var baseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                        var titleFont = new iTextSharp.text.Font(baseFont, 18, iTextSharp.text.Font.BOLD);
                        var normalFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL);

                        // 标题
                        var title = new Paragraph("PDF生成测试", titleFont);
                        title.Alignment = Element.ALIGN_CENTER;
                        title.SpacingAfter = 20f;
                        document.Add(title);

                        // 内容
                        var content = new Paragraph("这是一个测试PDF文档，用于验证iTextSharp是否正常工作。", normalFont);
                        content.SpacingAfter = 10f;
                        document.Add(content);

                        var content2 = new Paragraph($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}", normalFont);
                        document.Add(content2);
                    }
                    catch (Exception ex)
                    {
                        // 如果字体出现问题，使用默认字体
                        var fallbackFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
                        document.Add(new Paragraph($"PDF Generation Test - {DateTime.Now}", fallbackFont));
                        document.Add(new Paragraph($"Error with Chinese font: {ex.Message}", fallbackFont));
                    }

                    document.Close();
                    
                    var fileName = $"PDF测试_{DateTime.Now:yyyyMMddHHmmss}.pdf";
                    return File(stream.ToArray(), "application/pdf", fileName);
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { message = $"PDF生成测试失败：{ex.Message}", details = ex.ToString() });
            }
        }
    }
} 